//
//  FriendsListViewController.m
//  A Learning Walk
//
//  Created by wudongyang on 16/6/28.
//  Copyright © 2016年 战斗民族. All rights reserved.
//

#import "FriendsListViewController.h"
#import "AppDelegate.h"
#import "UserModel.h"
#import <objc/runtime.h>
#import "MyTableView.h"
#import "NewFriendsViewController.h"
#import "ChatViewController.h"
// 签订环信协议
@interface FriendsListViewController ()<UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate,EMChatManagerChatDelegate>
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSArray *array;
// 好友用户名
@property (nonatomic, copy) NSString *userName;
// 临时使用
@property (nonatomic, retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableDictionary *myUserDic;
@property (nonatomic, retain) NSMutableArray *myKeyArray;
// 创建新的好友按钮
@property (nonatomic, retain)UIButton *NewFriendsButton;
@end

@implementation FriendsListViewController
- (void)dealloc
{
    [_myTableView release];
    [_array release];
    [_userName release];
    [_myArray release];
    [_myUserDic release];
    [_myKeyArray release];
    [_NewFriendsButton release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.myUserDic = [NSMutableDictionary dictionary];
    [self createView];
    // 获取环信好友数据
    [self createData];
    
    // 导航栏右按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(BarAction:)];
    // 导航栏左按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarItemAction:)];
    // 导航栏标题
    self.navigationItem.title = @"我的好友";
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem]
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self createData];
    // 转为本地数据
//    [self key:self.myArray];
//    // 所有key排序后组成的数组
//    self.myKeyArray = [NSMutableArray arrayWithArray:self.myUserDic.allKeys];
}
- (void)BarAction:(UIBarButtonItem *)bar {
//    好友请求
    [self buddyRequest];
}
// 环信协议方法.获取好友列表
- (void)didFetchedBuddyList:(NSArray *)buddyList
                      error:(EMError *)error {
    NSLog(@"%@",buddyList);
}
- (void)createView {
    self.myTableView = [[MyTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [_myTableView release];
    // 签订环信代理
    [[[EaseMob sharedInstance] chatManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    headView.backgroundColor = [UIColor yellowColor];
    self.myTableView.tableHeaderView = headView;
    [headView release];
    // 创建新好友按钮
    self.NewFriendsButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.NewFriendsButton.backgroundColor = [UIColor whiteColor];
    self.NewFriendsButton.frame = CGRectMake(0, 0, WIDTH, 40);
    [self.NewFriendsButton addTarget:self action:@selector(NewFriendsButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.NewFriendsButton];
    UIImageView *NewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 30, 30)];
    NewImageView.image = [UIImage imageNamed:@"newFriends"];
    NewImageView.backgroundColor = [UIColor yellowColor];
    [self.NewFriendsButton addSubview:NewImageView];
    [NewImageView release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, 100, 30)];
    label.text = @"新的朋友";
    [self.NewFriendsButton addSubview:label];
    [label release];
    
    
}
// TableView的点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *key = [self.myKeyArray objectAtIndex:indexPath.section];
    NSArray *arrayTp = [self.myUserDic objectForKey:key];
    UserModel *model = [arrayTp objectAtIndex:indexPath.row];
    
    ChatViewController *ChatVC = [[ChatViewController alloc] init];
    ChatVC.chatter = model.userName;
    [self.navigationController pushViewController:ChatVC animated:YES];
    [ChatVC release];
    
}
#pragma mark 协议方法
//分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.myKeyArray.count;
}



//显示分区名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *sectonName = [self.myKeyArray objectAtIndex:section];
    NSLog(@"111111");
    return sectonName;
}
// 每个分区cell 的个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"===========");
    NSString *key = [self.myKeyArray objectAtIndex:section];
    NSLog(@"%lu",[[self.myUserDic objectForKey:key] count]);
    return [[self.myUserDic objectForKey:key] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //添加cell
    NSString *key = [self.myKeyArray objectAtIndex:indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    //赋值
    NSArray *arrayTp = [self.myUserDic objectForKey:key];
    UserModel *model = [arrayTp objectAtIndex:indexPath.row];
    NSLog(@"%@",model.userName);
    cell.textLabel.text  = model.userName;
    NSLog(@"111");
    return cell;
    
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView  {
//    // 查找tableView的私有属性
//    unsigned  int count = 0;
//    Ivar *ivarles = class_copyIvarList([UITableView class], &count);
//    for (int i = 0; i < count; i++) {
//        NSLog(@"%s==%s",ivar_getName(ivarles[i]), ivar_getTypeEncoding(ivarles[i]));
//    }
    return self.myKeyArray;
}


// 环信协议方法, 自动登录
- (void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error {
    NSLog(@"dsfkjlsdf");
    if (!error) {
        NSLog(@"自动登录成功");
        NSLog(@"%@",loginInfo);
    } else {
        NSLog(@"%@",error);
    }
}



// 好友申请处理结果回调
- (void)didAcceptedByBuddy:(NSString *)username {
    
    NSLog(@"======================%@",username);
    
    
    NSLog(@"%@",username);

    // 重新获取好友列表刷新tableView
    [self createData];
    
}


- (void)didRejectedByBuddy:(NSString *)username {
    NSLog(@"%@",username);
}

// 好友申请
- (void)buddyRequest {
    NSLog(@"dsjkfkjlsdfkj");
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"好友申请" message:@"确定" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.tag = 12000;
        [textField addTarget:self action:@selector(textAction:) forControlEvents:UIControlEventEditingChanged];
        
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        EMError *error = nil;
        //环信的好友请求方法
        BOOL isSuccess = [[[EaseMob sharedInstance] chatManager] addBuddy:self.userName message:@"我想加你为好友" error:&error];
        NSLog(@"%@",self.userName);
        if (isSuccess && !error) {
            NSLog(@"添加好友成功");
        } else {
            NSLog(@"%d",isSuccess);
            NSLog(@"%@",error);
        }
        
    }]];
    [self presentViewController:alert animated:YES completion:^{
        
        
    }];
}

//获取环信好友列表
-(void)createData{
    
    // 环信获取好友列表的方法 用一个数组接收
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.myArray = [NSMutableArray array];
        NSArray *array = [[EaseMob sharedInstance].chatManager buddyList];
//        NSLog(@"%@",array);
        // 遍历这个数组
        for (EMBuddy *emb in array) {
            UserModel *model = [[UserModel alloc] init];
            model.userName = emb.username;
            [self.myArray addObject:model];
            [model release];

        }
        // 转为本地数据
        [self key:self.myArray];
        // 所有key排序后组成的数组
        self.myKeyArray = [NSMutableArray arrayWithArray:self.myUserDic.allKeys];
        [self.myTableView reloadData];
    });
//    NSLog(@"11111");
    
}


//创建字典
-(void)key:(NSMutableArray *)array{
    self.myUserDic = [NSMutableDictionary dictionary];
    for (UserModel *modelTemp in array) {
        // 截取字符串第一个字母变为大写
        NSString *key = [[modelTemp.userName substringToIndex:1] uppercaseString];
        // 如果字典首字母包含 这个首字母
        if ([[self.myUserDic allKeys] containsObject:key]) {
            
            NSMutableArray *arrayTemp = [self.myUserDic objectForKey:key];
            [arrayTemp addObject:modelTemp];
        }else{
            NSMutableArray *array1 = [NSMutableArray array];
            [array1 addObject:modelTemp];
            [self.myUserDic setObject:array1 forKey:key];
        }
    }
}


- (void)NewFriendsButtonAction:(UIButton *)button{
    NSLog(@"新的朋友按钮点击方法");
    NewFriendsViewController *NewFriendVC = [NewFriendsViewController new];
    [self.navigationController pushViewController:NewFriendVC animated:YES];
}
- (void)textAction:(UITextField *)text {
    self.userName = text.text;
}
// 导航栏左按钮返回方法
- (void)leftBarItemAction:(UIBarButtonItem *)item{
[self dismissViewControllerAnimated:YES completion:^{
    
    
}];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
